/**$Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *   Copyright (C) 2008 - 2013 xingsheng.zhu@gmail.com All rights reserved.
 */
package com.blazemina.executor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import com.blazegame.logging.Logger;
import com.blazegame.logging.LoggerFactory;
import com.blazemina.CommandContext;

/**
 * @author JackChu
 * @version 2.0.0 2013-2-21 下午1:27:34
 */
public class ThreadpoolBlazeminaExecutors implements BlazeminaExecutors {

	private final static Logger logger = LoggerFactory
			.getLogger(ThreadpoolBlazeminaExecutors.class);

	private final Map<String, ExecutorGroup> executorGroups = new HashMap<String, ExecutorGroup>();

	@Override
	public void addExecutorGroup(String groupName, int groupSize,
			boolean sequence) {
		if (executorGroups.containsKey(groupName)) {
			logger.error("add executor group error,this groupName:" + groupName
					+ " has exist");
		} else {
			executorGroups.put(groupName, new ExecutorGroup(groupName,
					groupSize, sequence));
		}
	}

	@Override
	public void execute(final CommandContext commandContext, RouteInfo routeInfo) {
		ExecutorGroup executorGroup = executorGroups.get(routeInfo
				.getGroupName());
		ExecutorService executor = executorGroup.getExecutor(routeInfo);
		executor.execute(new Runnable() {
			@Override
			public void run() {
				CommandMethodExecutor.execute(commandContext);
			}
		});
	}

	@Override
	public boolean isThreadPool() {
		return true;
	}

}
